package cn.sunxyz.module.honey.service;

import cn.sunxyz.common.util.SiteFetchedUtil;
import cn.sunxyz.module.honey.domain.SiteDO;
import cn.sunxyz.module.honey.repository.SiteRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Objects;

/**
 * Created by sunxyz on 2017/3/2.
 */
@Service
public class SiteService {

    @Autowired
    private SiteRepository siteRepository;

    private String rootPath;

    @Autowired
    public SiteService(HttpServletRequest request) {
        this.rootPath = request.getSession().getServletContext().getRealPath("/");
    }

    public SiteDO getSiteByUrl(String url) {
        // 文件存放服务端的位置
        String upload = "/upload/ico/";
        //TODO 判斷url是否合法
        SiteDO site = siteRepository.findByUrl(url);
        if (Objects.isNull(site)) {
            site = new SiteDO();
            Date now = new Date();
            site.setCreateTime(now);
            site.setUpdateTime(now);
            site.setUrl(url);
            //TODO 抓取 title icon
            site.setIcon(upload + SiteFetchedUtil.downloadICO(SiteFetchedUtil.getDomain(url), rootPath + upload));
            site.setTitle(SiteFetchedUtil.get(url).get().title());
            site = siteRepository.save(site);
        }
        return site;
    }
}
